package com.lt.service.impl;

import com.lt.dto.*;
import com.lt.entity.*;
import com.lt.mapper.FileMapper;
import com.lt.mapper.ProjectMapper;
import com.lt.mapper.StudentMapper;
import com.lt.service.ProjectService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author :liteng
 * @Time : 2023/11/5 21:26
 */

@Service
@Slf4j
public class ProjectServiceImpl implements ProjectService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private final ProjectMapper projectMapper;

    private final StudentMapper studentMapper;

    private final FileMapper fileMapper;


    public ProjectServiceImpl(ProjectMapper projectMapper, StudentMapper studentMapper, FileMapper fileMapper) {
        this.projectMapper = projectMapper;
        this.studentMapper = studentMapper;
        this.fileMapper = fileMapper;
    }

    //    @Cacheable(value = "projectApplyCache",key = "#myProjects")
    @Override
    public List<MyProject> getAllProject() {
        //从项目立项审核表中查询数据
        //向redis中添加数据
        List<MyProject> myProjects = null;
        //根据键值取出数据

//        myProjects = (List<MyProject>) redisTemplate.opsForValue().get("myProjects1");
        myProjects = getMyProjects(1);
//            redisTemplate.opsForValue().set("myProjects1", myProjects);
        //        myProjects = getMyProjects(1);
        return myProjects;
    }

    private List<MyProject> getMyProjects(int table) {
        List<MyProject> myProjects = projectMapper.selectAllMyProject(table);
        myProjects.forEach(item -> {
            Long id = item.getId();
            Student student = projectMapper.selectChargeStu(id);
            item.setDirector(student.getName());
            item.setDepartment(student.getDepartment());
            String teacher = projectMapper.selectTeacher(id);
            item.setTeacherName(teacher);
            Project project = projectMapper.selectProject(id);
            item.setName(project.getName());
            item.setNumber(project.getNumber());
            item.setCategory(project.getCategory());

        });
        return myProjects;
    }

    public MyProject getMyProjects(Long projectId) {
//        List<MyProject> myProjects = projectMapper.selectAllMyProject(table);
        MyProject item = new MyProject();
        Student student = projectMapper.selectChargeStu(projectId);

        item.setDirector(student.getName());
        item.setDepartment(student.getDepartment());
        String teacher = projectMapper.selectTeacher(projectId);
        item.setTeacherName(teacher);
        Project project = projectMapper.selectProject(projectId);
        item.setName(project.getName());
        item.setNumber(project.getNumber());
        item.setCategory(project.getCategory());

        return item;
    }

    @Override
    public ProjectApply getProjectDetails(Long projectId) {

        ProjectApply apply = new ProjectApply();
        Project project = projectMapper.selectProjectDetails(projectId);

        apply.setName(project.getName());
        apply.setCategory(project.getCategory());
        apply.setNumber(project.getNumber());
        apply.setIntroduction(project.getIntroduction());
        apply.setExecutionDate(project.getExecutionDate());

        List<StudentApplyDto> dtos = projectMapper.selectJoinStudents(projectId);
        Iterator<StudentApplyDto> iterator = dtos.iterator();
        while (iterator.hasNext()) {
            StudentApplyDto applyDto = iterator.next();
            if (applyDto.getInCharge() == 1) {
                //设置负责人
                apply.setPersonInCharge(applyDto);
                //移除负责人
                iterator.remove();
            }
        }
//        dtos.forEach(applyDto -> {
//
//        });
        apply.setStudents(dtos);

        apply.setPersonNum(dtos.size());

        Teacher teacher = projectMapper.selectTeacherDetails(projectId);
        apply.setTeacher(teacher);

        Tutor tutor = projectMapper.selectTutor(projectId);
        apply.setTutor(tutor);

        List<File> files = projectMapper.selectFilesByProject(projectId);

        Files newFiles = new Files();
        List<Files.Data> dataList = new ArrayList<>();
        files.forEach(item -> {
            String fileName = item.getFileName();
            Long id = item.getId();
            String link = item.getLink();
            dataList.add(new Files.Data(fileName, id, link));
//            files1.setData(data);
        });

        newFiles.setNum(files.size());
        newFiles.setData(dataList);

        apply.setFiles(newFiles);

        return apply;
    }

    @Override
    public List<StudentApplyDto> getJoinedStudents(Long projectId) {
        List<StudentApplyDto> students = projectMapper.selectJoinStudents(projectId);
//        Iterator<StudentApplyDto> iterator = students.iterator();
//        while (iterator.hasNext()) {
//            StudentApplyDto applyDto = iterator.next();
//            if (applyDto.getInCharge() == 1) {
//                //设置负责人
//                students.setPersonInCharge(applyDto);
//                //移除负责人
//                iterator.remove();
//            }
//        }
        return students;
    }

    @Override
    public Student getChargeStu(Long projectId) {
        List<StudentApplyDto> dtos = projectMapper.selectJoinStudents(projectId);
        for (StudentApplyDto applyDto : dtos) {
            if (applyDto.getInCharge() == 1) {
                return applyDto;
            }
        }
        return null;
    }

    @Override
    public String getUnPassedReason(Long projectId) {
        return projectMapper.selectDetails(projectId, 1);
    }

    @Override
    public List<ProgressRecord> getRecords() {
        List<MyProject> myProjects = getMyProjects(2);
        List<ProgressRecord> records = new ArrayList<>();
        myProjects.forEach(i -> {
            ProgressRecord record = new ProgressRecord();
            BeanUtils.copyProperties(i, record);

            record.setSubmissionTimes(projectMapper.selectTimesById(i.getId()));
            records.add(record);
        });

//        ProgressRecord progressRecord = new ProgressRecord();

        return records;
    }

    @Transactional
    @Override
    public void submitLog(Long projectId, Long fileId) {
        projectMapper.updateSubmitFileTimes(projectId);
        projectMapper.updateSubmitStatus(2, projectId);
        projectMapper.insertLogFile(projectId, fileId);
    }

    @Override
    public List<InterimReviewDto> getReview() {
        List<InterimReviewDto> reviewDtos = new ArrayList<>();
        List<MyProject> myProjects = getMyProjects(2);
        myProjects.forEach(i -> {

            InterimReviewDto dto = new InterimReviewDto();
            BeanUtils.copyProperties(i, dto);
            Long id = i.getId();
            List<String> member = projectMapper.selectMember(id);
            String m = String.join(",", member);
            int status = projectMapper.selectInterimStatus(id);
            String details = projectMapper.selectDetails(id, 2);
            dto.setMember(m);
            dto.setDetails(details);
//            dto.setInterimStatus(status);
            reviewDtos.add(dto);
        });
        return reviewDtos;
    }

    @Transactional
    @Override
    public Boolean changeMember(ChangeMemberDto changeMemberDto) {
        if (changeMemberDto == null) {
            return false;
        }
        Long projectId = changeMemberDto.getProjectId();
        projectMapper.deleteStuJoin(projectId);
        List<StudentApplyDto> students = changeMemberDto.getStudents();
        for (StudentApplyDto stu : students) {
            Long stuId = studentMapper.selectStuId(stu.getStuNum());
            log.info("项目成员id" + stuId);
            projectMapper.insertJoin(stuId, stu, projectId);
        }

        return true;
    }

    @Override
    public String getInterimReason(Long projectId) {
        String s = projectMapper.selectDetails(projectId, 2);
        return s;
    }

    @Override
    public List<ClosingAuditDto> getEndList() {
        List<ClosingAuditDto> reviewDtos = new ArrayList<>();
        List<MyProject> myProjects = getMyProjects(3);
        myProjects.forEach(i -> {
            ClosingAuditDto dto = new ClosingAuditDto();
            BeanUtils.copyProperties(i, dto);

            List<String> member = projectMapper.selectMember(i.getId());
            int i1 = projectMapper.selectSubmitted(i.getId());
            String m = String.join(",", member);
            dto.setMember(m);
            dto.setDetails("");
            dto.setIsSubmitted(i1);
            reviewDtos.add(dto);
        });
        return reviewDtos;
    }

    @Override
    public ClosingAuditDto getEndListOne(Long ig) {
        ClosingAuditDto dto = new ClosingAuditDto();

        return null;
    }

    @Override
    public String getEndReason(Long projectId) {
        return projectMapper.selectDetails(projectId, 3);
    }

    @Override
    @Transactional
    public Boolean closingMaterial(ClosingMaterial closingMaterial) {
        Long projectId = closingMaterial.getProjectId();
        int status = projectMapper.selectStatus(projectId);
        int submitted = projectMapper.selectSubmitted(projectId);
        boolean flag = true;
        log.error(String.valueOf(status));
        log.error(String.valueOf(submitted));
        if (status == 1 && submitted == 0) {
            if (closingMaterial.getHasPaper()) {
                int i = projectMapper.insertPaper(projectId, closingMaterial.getPaper());
                if (i != 1) {
                    flag = false;
                    log.info("插入论文失败");
                } else
                    log.info("插入论文成功");

            }
            if (closingMaterial.getHasPatent()) {
                int i = projectMapper.insertPatent(projectId, closingMaterial.getPatent());
                if (i != 1) {
                    flag = false;
                    log.info("插入专利失败");
                } else
                    log.info("插入专利成功");
//                log.info("插入成功");
            }
            if (closingMaterial.getHasPhysicalWork()) {
                int i = projectMapper.insertPhysicalWork(projectId, closingMaterial.getPhysicalWork());
                if (i != 1) {
                    flag = false;
                    log.info("插入实物作品失败");
                } else
                    log.info("插入实物作品成功");
            }
        } else {
            flag = false;
        }
        if (flag) {
            Files files = closingMaterial.getFiles();
            List<Files.Data> data = files.getData();
            //添加文件
            for (Files.Data data1 : data) {
                fileMapper.insertEndFile(projectId, data1.getId());
            }
            if (projectMapper.updateEndSubmitted(1, projectId) != 1) {
                flag = false;
            }
        }
        return flag;
    }


    @Override
    public Boolean delayedReview(Long projectId, String reason) {
        int status = 4;
        return projectMapper.updateEndStatus(projectId, status, reason) == 1;
    }

    @Override
    public String showEndDetails(Long projectId) {
        return projectMapper.selectDetails(projectId, 3);
    }


//    @Override
//    public ProjectEnd getEndItem(Long projectId) {
//        ProjectEnd end = projectMapper.selectOneEnd(projectId);
//        return null;
//    }


//    @Override
//    public Integer getInterimStatus(Long projectId) {
//        return null;
//    }

//    @Override
//    public Integer getInterimStatus(Long projectId) {
//        return projectMapper.selectInterimStatus(projectId);
//    }
}
